﻿using System.Threading;
using Client.Interfaces;
using Global.Interfaces.Server;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System;
using System.Text;
using Client.secureMessengerServer;

namespace Client.Controllers
{
    internal class InvitationInitiator
    {
        public static void InviteBuddy(IMainController main, IBuddy buddyToContact, string chatEndpoint, string chatPassword)
        {
            ContactBuddyDirectly(buddyToContact, chatEndpoint, chatPassword);
            SendChatToServer(main, buddyToContact, chatEndpoint, chatPassword);
        }

        private static void SendChatToServer(IMainController main, IBuddy buddyToContact, string chatEndpoint, string chatPassword)
        {
            secureMessengerServer.IsMessengerServerClient server = new IsMessengerServerClient("secureMessengerServerEndpoint");
            server.ClientCredentials.ClientCertificate.Certificate = Certificate.CertificateLoader.GetClientCertificate(main.Password);
            server.BeginAddChat(main.Username, buddyToContact.Username, chatEndpoint, chatPassword, null, null);
        }

        private static void ContactBuddyDirectly(IBuddy buddyToContact, string chatEndpoint, string chatPassword)
        {
            CustomBinding binding = new CustomBinding(new TcpTransportBindingElement());
            string address = GetAddress(buddyToContact);
            EndpointAddress endpoint = new EndpointAddress(address);
            secureMessengerClient.IncomingChatServiceClient client = new Client.secureMessengerClient.IncomingChatServiceClient("secureMessengerClientEndpoint", endpoint);
            client.BeginStartChat(chatEndpoint, chatPassword, null, null);
        }

        private static string GetAddress(IBuddy buddyToContact)
        {
            StringBuilder sb = new StringBuilder("net.tcp://");
            if (buddyToContact.Ip.Contains(":"))
                sb.Append("[");
            sb.Append(buddyToContact.Ip);
            if (buddyToContact.Ip.Contains(":"))
                sb.Append("]");
            sb.Append(":");
            sb.Append(buddyToContact.Port.ToString());
            sb.Append("/P2P/client");
            string address = sb.ToString();
            return address;
        }
    }
}
